package com.unohacha.qqj.fzdr.imp;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.multidex.MultiDex;
import android.util.Log;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.huangmin66.rongcloud.RongCloudUtils;
import com.lzy.ninegrid.NineGridView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.qpg.superhttp.SuperHttp;
import com.qpg.widget.WidgetInit;
import com.tencent.smtt.sdk.QbSdk;
import com.unohacha.qqj.fzdr.MainActivity;

import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.login.LoginActivity;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.view.PublicStaticData;
import com.unohacha.qqj.mylibrary.AppManager;

import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Stack;

/**
 * Created by Administrator on 2018/5/15 0015.
 */

public class MyApplication extends Application {
    private static final String TAG = "MyApplication";
    private static Stack<Activity> activityStack = new Stack<>();
    public static final boolean isDebug = true;//是否为调试模式
    private static MyApplication instance;
    public static Context mContext;
    /**
     * 应用未启动, 个推 service已经被唤醒,保存在该时间段内离线消息(此时 GetuiSdkDemoActivity.tLogView == null)
     */
    public static StringBuilder payloadData = new StringBuilder();

    private static DemoHandler handler;
    public static MainActivity demoActivity;

    public static DisplayImageOptions imageLoaderOptions = new DisplayImageOptions.Builder()//
            .showImageOnLoading(R.drawable.ic_default_image)         //设置图片在下载期间显示的图片
            .showImageForEmptyUri(R.drawable.ic_default_image)       //设置图片Uri为空或是错误的时候显示的图片
            .showImageOnFail(R.drawable.ic_default_image)            //设置图片加载/解码过程中错误时候显示的图片
            .cacheInMemory(true)                                //设置下载的图片是否缓存在内存中
            .cacheOnDisk(true)                                  //设置下载的图片是否缓存在SD卡中
            .build();                                           //构建完成

    public static ImageOptions xUtilsOptions = new ImageOptions.Builder()//
            .setIgnoreGif(false)                                //是否忽略GIF格式的图片
            .setImageScaleType(ImageView.ScaleType.FIT_CENTER)  //缩放模式
            .setLoadingDrawableId(R.drawable.ic_default_image)       //下载中显示的图片
            .setFailureDrawableId(R.drawable.ic_default_image)       //下载失败显示的图片
            .build();
    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        mContext = getApplicationContext();
        NineGridView.setImageLoader(new GlideImageLoader());
        if (handler == null) {
            handler = new DemoHandler();
        }
        ImageLoaderConfiguration config = ImageLoaderConfiguration.createDefault(this);

        ImageLoader.getInstance().init(config);     //UniversalImageLoader初始化
        x.Ext.init(this);
        RongCloudUtils.init(this);
        WidgetInit.init(this);
        SuperHttp.init(this);
        SuperHttp.config()
                //配置请求主机地址
                .setBaseUrl(UrlConfig.BASE_URL+"/");

        PublicStaticData.sharedPreferences=getSharedPreferences("fzdr",MODE_PRIVATE);

        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                Log.d("app", " onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(),  cb);
        //友盟
        UMShareAPI.get(this);
        Config.DEBUG = false;
        initShareAuth();
        
    }

    private void initShareAuth() {
        //需要分享的平台的appkey 和 App Secret
        PlatformConfig.setWeixin("wx0ec36cddf5808a3c", "e91dc6708a6f43ab3e8478c756ce85b5");
        //空间填写是AppID和App Key
        PlatformConfig.setQQZone("1106473352", "dXscv6WNrpKOt3iR");
    }
    
    public static MyApplication getInstance() {
        if (instance == null) {
            instance = new MyApplication();
            instance.onCreate();
        }
        return instance;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    /**
     * Glide 加载
     */
    private class GlideImageLoader implements NineGridView.ImageLoader {

        @Override
        public void onDisplayImage(Context context, ImageView imageView, String url) {
            Glide.with(context).load(url)//
                    .placeholder(R.drawable.ic_default_image)
//                    .apply(new RequestOptions().placeholder(R.drawable.ic_default_image))
//                    .error(R.drawable.ic_default_image)
                    .into(imageView);
        }

        @Override
        public Bitmap getCacheImage(String url) {
            return null;
        }
    }

    //往栈中添加activity
    public void addActivity(Activity activity) {
        if (activity != null) {
            activityStack.add(activity);
            recordActivity(activity);
        }
    }

    //从栈中移出activity
    public void removeActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
        }
    }

    //依次销毁activity
    private void finishActivity() {
        for (int i = 0; i < activityStack.size(); i++) {
            if (activityStack.get(i) != null && !activityStack.get(i).isFinishing()) {
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
    }

    private void finishActivity2() {
        AppManager.getAppManager().finishAllActivity();
    }

    /**
     * 跳转到登录界面
     */
    public void gotoLoginActivity() {
        Prefer.getInstance().clearData();
        finishActivity2();
        Intent intent = new Intent();
        intent.setClass(this, LoginActivity.class);
        Bundle bundle = new Bundle();
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    /**
     * 仅返回登录页面
     */
    public void BackLoginActivity() {

        SharedPreferences sd = getSharedPreferences("userinfo", 0);
        SharedPreferences.Editor editor = sd.edit();
        editor.clear();
        editor.commit();
        Prefer.getInstance().setToken("");

        Intent intent = new Intent();
        intent.setClass(this, LoginActivity.class);
        Bundle bundle = new Bundle();
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }


    //退出登录
    public void exit(Activity activity) {
//        SharedPreferences sd = getSharedPreferences("userinfo", 0);
//        SharedPreferences.Editor editor = sd.edit();
//        editor.clear();
//        editor.commit();
//        infoBean.setToken("");
//        Prefer.getInstance().clearData();
        finishActivity();
        if (activity != null && !activity.isFinishing()) {
            activity.finish();
        }
    }


    //记录所有当前存活在内存的activity对象
    private static ArrayList arrayList = new ArrayList();

    //记录当前活着的activity，方便测试
    private void recordActivity(Activity activity) {
        ArrayList list = new ArrayList();
        for (Object object : arrayList) {
            if (((WeakReference) object).get() == null) {
                list.add(object);
            }
        }
        if (list.size() > 0) {
            arrayList.removeAll(list);
        }
        WeakReference weakReference = new WeakReference(activity);
        arrayList.add(weakReference);
        Log.i("TAG", "当前所有Activity：");
        for (Object object : arrayList) {
            if (object != null && ((WeakReference) object).get() != null) {
                Log.i("TAG", ((WeakReference) object).get().toString());
            }
        }
    }

    public static String getToken() {
        return Prefer.getInstance().getToken();
    }

    public static void setToken(String token) {//type
        Prefer.getInstance().setToken(token);

        SharedPreferences sp = getInstance().getSharedPreferences("user", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor2 = sp.edit();
        editor2.putString("token", token);
        editor2.commit();

        SharedPreferences sd = getInstance().getSharedPreferences("userinfo", 0);
        SharedPreferences.Editor editor = sd.edit();
        editor.putString("token", token);
        editor.commit();

    }

    public static void sendMessage(Message msg) {
        handler.sendMessage(msg);
    }

    public static class DemoHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (demoActivity != null) {
                        payloadData.append((String) msg.obj);
                        payloadData.append("\n");
//                        if (MainActivity.tLogView != null) {
//                            MainActivity.tLogView.append(msg.obj + "\n");
//                        }
                    }
                    break;

                case 1:
                    if (demoActivity != null) {
//                        if (MainActivity.tLogView != null) {
//                            MainActivity.tView.setText((String) msg.obj);
//                        }
                    }
                    break;
            }
        }
    }
}
